package com.yu.newsSys.service.impl;

import com.yu.newsSys.dao.NewsDao;
import com.yu.newsSys.domain.News;
import com.yu.newsSys.service.NewsService;
import com.yu.newsSys.utils.CommonUtils;
import com.yu.newsSys.vo.Page;
import com.yu.newsSys.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
public class NewsServiceImpl implements NewsService {

    @Autowired
    NewsDao newsDao;

    @Override
    public Result getNews(String newsPaperName, String fileTitle, Integer currentPage, Integer pageSize) {

        Integer total = newsDao.getTotal(newsPaperName, fileTitle);

        Integer start = (currentPage - 1) * pageSize;
        List<News> list = newsDao.getNews(newsPaperName, fileTitle,start,pageSize);
        int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        Page<News> page = new Page<>(currentPage, pageSize, totalPages, total, list);
        System.out.println(page.toString());
        return Result.OK(page);
    }

    @Override
    public Result add(News news) {
        CommonUtils.logInfo("add","service",news);
        int count = newsDao.add(news);
        if (count == 1) {
            return Result.OK();
        } else {
            return Result.ERROR();
        }
    }

    @Override
    public Result getNewsById(int id) {
        CommonUtils.logInfo("getNewsById","service",id);
        News news = newsDao.getNewsById(id);
        if (news != null) {
            return Result.OK(news);
        } else {
            return Result.ERROR();
        }
    }

    @Override
    public Result edit(News news) {

        int count = newsDao.update(news);
        if (count == 1) {
            return Result.OK();
        } else {
            return Result.ERROR();
        }
    }

    @Transactional
    @Override
    public Result remove(int id) {
        CommonUtils.logInfo("remove","service",id);
        int count = newsDao.delete(id);

        // 测试事务 自定义错误
        int a = 1 / 0;
        
        if (count == 1) {
            return Result.OK();
        } else {
            return Result.ERROR();
        }
    }

}
